//
//  HomeVC.m
//  YangWifi
//
//  Created by zuoxueliangduyuanzhuo on 2017/6/10.
//  Copyright © 2017年 zuoxueliangduyuanzhuo. All rights reserved.
//

#import "HomeVC.h"
#import "HomeRecommendV.h"
#import "LoginVC.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <RealReachability/RealReachability.h>
#import "ProductDetailVC.h"
#import "ProductListVC.h"
//#import <HuangQiSDK/HuangQiSDK.h>
#import <HuangQiSDK/HuangQiConnect.h>
@interface HomeVC ()

@property (nonatomic ,strong) HomeRecommendV *recommendV;

@property (nonatomic ,strong) UILabel *wifiStateL;

@property (nonatomic ,strong) UILabel *wifiNameL;

@property (nonatomic ,strong) UIButton *wifiLinkBtn;

@property (nonatomic ,strong) UIImageView *wifiImgV;

@property (nonatomic ,strong)HuangQiConnect *connect;

@end

@implementation HomeVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self  networkStatus];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self.connect start:@"774d76467461616a654242657952357941547252642b3133684549587974665935444b6a596b77433937495156464c34644c35544b2b325a782b69636a6d4a336357534f31346c566f32724c59786c6334574e6c515a3751565a613762313555744c786345736e635257737230414e6f6839724d6a6449593172774e54753049703669654a644a65324135586d56767934716c7730704c79776b4777367569384b32347649547333675a6a554d756e5639776d3650644b3250624f3374485a494c4e584633724d334f345a5162346a2b637645563742477a3457357537723052545a66716a75536130556a4648446a414b4b745773634b6f5a345431736d487844463051684b70626d635a325677416f59706f5848467257376c54396c434f3176494943554f5a374e4679624e38624768542f795446327262345335324e5447687036504d455a3262497a702b6f66586458656a414d52497258326b4e32634f4e657170397a6142632f386d412b6a396e34574357652f486e66616f3155545a33792b32732f383352476d4c57585850764d6b6853694b4978524863426b7a6d442b4761623745624b30513247596f6a75516c5761797a666f7678726e622b30742f504c575476797a44785a5a767037672f67436f673d3d" bundleldenfitier:@"com.deppon.YangCongWifi"];
   
}
- (NSString *)getWifiName
{
    NSString *wifiName = nil;
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);
    return wifiName;
}

- (void)networkStatus
{
    [GLobalRealReachability reachabilityWithBlock:^(ReachabilityStatus status) {
        switch (status)
        {
            case RealStatusUnknown:{
                
                self.wifiNameL.text = @"未知网络";
                self.wifiStateL.text = @"请检查你的网络是否连接";
                self.wifiImgV.image = [UIImage imageNamed:@"home_wifi_normal"];
                self.wifiLinkBtn.selected = NO;
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateHighlighted];

                break;
            }
            case RealStatusNotReachable:
            {
                //  case NotReachable handler
                self.wifiNameL.text = @"Wi-Fi未打开";
                self.wifiStateL.text = @"请检查你的网络是否连接";
                self.wifiImgV.image = [UIImage imageNamed:@"home_wifi_normal"];
                self.wifiLinkBtn.selected = NO;
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateSelected];
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateHighlighted];
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateNormal];
                break;
            }
                
            case RealStatusViaWiFi:
            {
                //  case ReachableViaWiFi handler
                
                NSString *wifi = [self getWifiName];
                DLog(@"wifi-%@",wifi);
                
                self.wifiNameL.text = wifi;
                self.wifiStateL.text = @"连接成功";
                self.wifiImgV.image = [UIImage imageNamed:@"home_wifi_selected"];
                self.wifiLinkBtn.selected = YES;
                [_wifiLinkBtn setTitle:@"切换其他Wi-Fi" forState:UIControlStateSelected];
                [_wifiLinkBtn setTitle:@"切换其他Wi-Fi" forState:UIControlStateHighlighted];
                [_wifiLinkBtn setTitle:@"切换其他Wi-Fi" forState:UIControlStateNormal];
                break;
            }
                
            case RealStatusViaWWAN:
            {
                //  case ReachableViaWWAN handler
                
                NSString *wifi = [self getWifiName];
                WWANAccessType accessType = [GLobalRealReachability currentWWANtype];
                DLog(@"wifi-%@",wifi);
                
                self.wifiNameL.text = @"Wi-Fi未打开";
                self.wifiImgV.image = [UIImage imageNamed:@"home_wifi_normal"];
                self.wifiLinkBtn.selected = NO;
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateSelected];
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateHighlighted];
                [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateNormal];                if (accessType == WWANType4G) {

                    self.wifiStateL.text = @"您正在使用4G网络";
                    
                }else if (accessType == WWANType3G){
                    
                    self.wifiStateL.text = @"您正在使用3G网络";
                    
                }else if (accessType == WWANType2G){
                    
                    self.wifiStateL.text = @"您正在使用2G网络";
                    
                }else if (accessType == WWANTypeUnknown){
                    
                    self.wifiStateL.text = @"未知网络";
                    
                }
                
                break;
            }
                
            default:
                break;
        }
    }];
}

- (void)networkChanged:(NSNotification *)notification
{
    [self networkStatus];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = xlHexColor(@"");
    self.navigationController.navigationBarHidden = YES;
    [self buildUIStyle];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkChanged:)
                                                 name:kRealReachabilityChangedNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshPackageListData) name:@"packageList" object:nil];

    self.connect  = [[HuangQiConnect alloc]init];
    [self.connect reset];
//    开启自动连接
    [self.connect start:@"774d76467461616a654242657952357941547252642b3133684549587974665935444b6a596b77433937495156464c34644c35544b2b325a782b69636a6d4a336357534f31346c566f32724c59786c6334574e6c515a3751565a613762313555744c786345736e635257737230414e6f6839724d6a6449593172774e54753049703669654a644a65324135586d56767934716c7730704c79776b4777367569384b32347649547333675a6a554d756e5639776d3650644b3250624f3374485a494c4e584633724d334f345a5162346a2b637645563742477a3457357537723052545a66716a75536130556a4648446a414b4b745773634b6f5a345431736d487844463051684b70626d635a325677416f59706f5848467257376c54396c434f3176494943554f5a374e4679624e38624768542f795446327262345335324e5447687036504d455a3262497a702b6f66586458656a414d52497258326b4e32634f4e657170397a6142632f386d412b6a396e34574357652f486e66616f3155545a33792b32732f383352476d4c57585850764d6b6853694b4978524863426b7a6d442b4761623745624b30513247596f6a75516c5761797a666f7678726e622b30742f504c575476797a44785a5a767037672f67436f673d3d" bundleldenfitier:@"com.deppon.YangCongWifi"];
    
//    [connect stop];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kRealReachabilityChangedNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"packageList" object:nil];

}

- (void)refreshPackageListData
{
    [self.recommendV buildData];
}

- (void)linkClick:(UIButton *)btn
{
    NSString * urlString = @"App-Prefs:root=WIFI";
    
    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
    
        if (IS_IOS_10) {
        
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
        }
    
    #else
    
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];

    #endif
}

- (void)payHandler:(ProductInfoModel *)infoModel
{
    if (![AccountHanler isLogin]) {
        
        LoginVC *loginVC = [[LoginVC alloc] initWithNibName:@"LoginVC" bundle:nil];
        loginVC.isNeedOrderNoti = YES;
        loginVC.isNeedHomeNoti = NO;
        @WeakObj(self);
        loginVC.loginHandler = ^{
            [Weakself pushPackageDetail:infoModel];
        };
        XLNavigationVC *nav = [[XLNavigationVC alloc] initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
        
    }else{

        [self pushPackageDetail:infoModel];

    }
}

- (void)pushPackageDetail:(ProductInfoModel *)infoModel
{
    
    NSDictionary *params = @{@"type":@"OSWIFI_PACKAGEDETAIL_MOBILE",
                             @"token":IsNull([AccountHanler token], @""),
                             @"requestEntity":@{
                                     @"id": IsNull(infoModel.id, @""),
                                     @"telephone":IsNull([AccountHanler telPhone], @"")}
                             };
    @WeakObj(self);
    [MHNetworkManager postReqeustWithURL:nil params:params successBlock:^(NSDictionary *returnData) {
        
        XLBaseModel *result = [XLBaseModel mj_objectWithKeyValues:returnData];
        if (result.resultFlag) {
            ProductDetailVC *vc = [[ProductDetailVC alloc] initWithNibName:@"ProductDetailVC" bundle:nil];
            vc.infoData = [ProductInfoModel mj_objectWithKeyValues:result.responseEntity[0]];
            [self.navigationController showViewController:vc sender:nil];
        }else{
            [Weakself.view makeToast:@"获取产品信息失败"];
        }
        
    } failureBlock:^(NSError *error) {
        [Weakself.view makeToast:@"获取产品信息失败"];
    } showHUD:YES];
}
#pragma mark-
#pragma mark 初始化UI界面

- (void)buildUIStyle
{
    [self buildBackgroundGradientColorLayer];

    UIImageView *ycImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_yc"]];
    [self.view addSubview:ycImgV];
    [self.view addSubview:self.wifiImgV];
    [self.view addSubview:self.wifiNameL];
    [self.view addSubview:self.wifiStateL];
    [self.view addSubview:self.wifiLinkBtn];
    [self.view addSubview:self.recommendV];
    [self refreshPackageListData];
    
    
    [ycImgV makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(32);
        make.centerX.equalTo(0);
        make.size.equalTo(CGSizeMake(55, 29));
    }];

    [self.wifiImgV makeConstraints:^(MASConstraintMaker *make) {
        make.top.lessThanOrEqualTo(ycImgV.bottom).offset(32).priority(10);
        make.top.greaterThanOrEqualTo(ycImgV.bottom).offset(16).priority(20);
        make.centerX.equalTo(0);
        make.size.equalTo(CGSizeMake(201, 161));
    }];
    
    [self.wifiNameL makeConstraints:^(MASConstraintMaker *make) {
        make.top.lessThanOrEqualTo(self.wifiImgV.bottom).offset(32).priority(30);
        make.top.greaterThanOrEqualTo(self.wifiImgV.bottom).offset(16).priority(30);
        make.left.equalTo(16);
        make.right.equalTo(-16);
        make.height.equalTo(33);
    }];

    
    [self.wifiStateL makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.wifiNameL.bottom).offset(4);
        make.left.equalTo(16);
        make.right.equalTo(-16);
        make.height.equalTo(22);
    }];
    
    [self.wifiLinkBtn makeConstraints:^(MASConstraintMaker *make) {
        make.top.lessThanOrEqualTo(self.wifiStateL.bottom).offset(32).priority(30);
        
        make.top.greaterThanOrEqualTo(self.wifiStateL.bottom).offset(16).priority(30);
        make.centerX.equalTo(0);
        make.width.equalTo(160);
        make.height.equalTo(40);
        make.bottom.equalTo(self.recommendV.top).offset(-100).priority(10);
    }];

    [self.recommendV makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(-49);
        make.right.left.equalTo(0);
        make.height.equalTo(96);
    }];

}

- (void)buildBackgroundGradientColorLayer
{
    /**
     *  1.通过CAGradientLayer 设置渐变的背景。
     */
    CAGradientLayer *layer = [CAGradientLayer new];
    //colors存放渐变的颜色的数组
    layer.colors=@[(__bridge id)xlHexColor(@"#165c4f").CGColor,(__bridge id)xlHexColor(@"#063f36").CGColor];
    /**
     * 起点和终点表示的坐标系位置，(0,0)表示左上角，(1,1)表示右下角
     */
    layer.startPoint = CGPointMake(0.5, 0);
    layer.endPoint = CGPointMake(0.5, 1);
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
}

- (void)pushPackageListVC
{
    ProductListVC *vc = [[ProductListVC alloc] initWithNibName:@"XLBaseEmptyTableVC" bundle:nil];
    [self showViewController:vc sender:nil];
}


- (HomeRecommendV *)recommendV
{
    if (!_recommendV) {
        _recommendV = [HomeRecommendV instanceHomeRecommendView];
        _recommendV.frame = CGRectMake(0, 0, SCREEN_WIDTH, 96);        
        @WeakObj(self);
        _recommendV.recommendHandler = ^(ProductInfoModel *infoModel){
            [Weakself payHandler:infoModel];
        };
        _recommendV.morePackageHandler = ^{
            [Weakself pushPackageListVC];
        };
    }
    return _recommendV;
}

- (UILabel *)wifiStateL
{
    if (!_wifiStateL) {
        _wifiStateL = [[UILabel alloc] init];
        _wifiStateL.text = @"正在使用4G网络";
        _wifiStateL.textColor = xlRGBA(255, 255, 255, 0.5);
        _wifiStateL.textAlignment = NSTextAlignmentCenter;
        _wifiStateL.font = xlFont(16);
    }
    return _wifiStateL;
}

- (UILabel *)wifiNameL
{
    if (!_wifiNameL) {
        _wifiNameL = [[UILabel alloc] init];
        _wifiNameL.text = @"WI-FI未打开";
        _wifiNameL.textColor = xlHexColor(@"#ffffff");
        _wifiNameL.textAlignment = NSTextAlignmentCenter;
        _wifiNameL.font = xlFont(24);
    }
    return _wifiNameL;
}

- (UIImageView *)wifiImgV
{
    if (!_wifiImgV) {
       
        _wifiImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_wifi_normal"]];

    }
    return _wifiImgV;
}

- (UIButton *)wifiLinkBtn
{
    if (!_wifiLinkBtn) {
        
        _wifiLinkBtn = [UIButton addTarget:self bgImageName:@"home_btn_bg" bgImageHighName:@"home_btn_bg" bgImageSelectedName:@"home_btn_bg" action:@selector(linkClick:)];
        _wifiLinkBtn.titleLabel.font = xlFont(16);
        [_wifiLinkBtn setTitleColor:xlRGBA(255, 255, 255, 0.75) forState:UIControlStateNormal];
        [_wifiLinkBtn setTitleColor:xlRGBA(255, 255, 255, 0.75) forState:UIControlStateHighlighted];
        [_wifiLinkBtn setTitleColor:xlRGBA(255, 255, 255, 0.75) forState:UIControlStateSelected];
        [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateSelected];
        [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateHighlighted];
        [_wifiLinkBtn setTitle:@"手动打开Wi-Fi" forState:UIControlStateNormal];
    }
    return _wifiLinkBtn;
}



@end
